package com.example.rental.controller;
import com.example.rental.entity.Admin;

import com.example.rental.entity.dto.AdminDto;
import com.example.rental.entity.dto.RegistDto;
import com.example.rental.result.Result;
import com.example.rental.service.AdminService;
import com.example.rental.util.WebUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/admin")
@Api(tags = "用户操作接口文档",description = "登录,注册，查看用户,搜索用户，修改用户")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public Map adminLogin(String phone, String password){
        Admin admin =new Admin();
        Map map=new HashMap();
            if(password != "" || password != null && phone != "" || phone != null) {
                admin=adminService.adminLogin(phone, password);
                if(admin.getState() !=0){
                if (admin!=null){
                    map.put("msg",admin);
                    return map;
                }
                }else {return map;}
            }
        return map;
    }
    @PostMapping("/insert")
    public Result addAdmin(@Validated @RequestBody RegistDto registDto, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            return WebUtils.getErrors(bindingResult);
        }

        if(adminService.findByPhone(registDto.getPhone()) != null){
            return Result.error(200,"该手机号已经被注册");
        }

        adminService.addAdmin(registDto.getPhone(),registDto.getPassword());

        return Result.ok();

    }
    @PostMapping("/search")
    public Result list(@RequestBody AdminDto adminDto){
        Result list = adminService.searchAdmin(adminDto);
        return list;
    }
    @PostMapping("/update")
    public Result updateAdmin(@RequestBody Admin admin){
        adminService.updateAdmin(admin);
        return Result.ok(admin);
    }

}
